package com.yjq.blog.article.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;

@Slf4j
@Component
public class WebSocketController extends TextWebSocketHandler {

    /**
     * socket 建立成功事件
     *
     * @param session
     * @throws Exception
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        log.info("---open");
    }

    /**
     * 接收消息事件
     *
     * @param session
     * @param message
     * @throws Exception
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        log.info("---message: {}", message.getPayload());
        sendMessage(session);
    }

    /**
     * socket 断开连接时
     *
     * @param session
     * @param status
     * @throws Exception
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        log.info("---close");
    }

    private void sendMessage(WebSocketSession session) {
        for (int i = 0; i < 100;) {

            i += Math.random() * 10;
            i = Math.min(i, 100);
            String res = String.valueOf(i);
            WebSocketMessage<String> message = new TextMessage(res);
            log.info(res);

            if (i > 60) {
                try {
                    session.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            try {
                session.sendMessage(message);
                Thread.sleep(500);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        try {
            session.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
